package com.agileai.bpm.interceptor.flow;

import com.agileai.bpm.common.VariableInterpreter;
import com.agileai.bpm.domain.define.Activity;
import com.agileai.bpm.domain.running.ActivityInstance;
import com.agileai.bpm.interceptor.BaseInterceptor;
import com.agileai.bpm.model.BizAttributeType;
import com.agileai.bpm.model.InterceptorModelDocument.InterceptorModel;
import com.agileai.bpm.model.WatchInvokerType;
import com.agileai.bpm.webservice.BPMService;
import com.agileai.bpm.webservice.BizAttribute;
import com.agileai.bpm.webservice.InvokeWorkItem;
import com.agileai.hotweb.common.BeanFactory;

public class ProcessInvokerInterceptor extends BaseInterceptor{
	private WatchInvokerType watchInvokerType;
	
	public ProcessInvokerInterceptor(InterceptorModel model,Activity activity){
		this.type = BaseInterceptor.Type.RestInvoker;
		this.isSynchronous = model.getSynchronous();
		this.variableCode = model.getVariableCode();
		this.varExpression = model.getVarExpression();
		
		this.watchInvokerType = model.getWatchInvoker();
	}
	
	public void doIntercept(ActivityInstance activityInstance) throws Exception  {
		BPMService bpmService = (BPMService)BeanFactory.instance().getBean("bpmService");
		
		InvokeWorkItem invokeWorkItem = new InvokeWorkItem();
		String processCode = watchInvokerType.getProcessCode();
		String bizRecordIdExp = watchInvokerType.getBizRecordId(); 
		String bizRecordId = VariableInterpreter.replaceVariables(bizRecordIdExp, activityInstance);
		
		invokeWorkItem.setBizRecordId(bizRecordId);
		invokeWorkItem.setActivityCode(watchInvokerType.getActivityCode());
		invokeWorkItem.setProcessCode(processCode);
		
		if (watchInvokerType.getBizAttributeArray() != null){
			for (int i=0;i < watchInvokerType.getBizAttributeArray().length;i++){
				BizAttributeType bizAttributeType = watchInvokerType.getBizAttributeArray(i);
				BizAttribute bizAttribute = new BizAttribute();
				bizAttribute.setCode(bizAttributeType.getCode());
				String expression = bizAttributeType.getValue();
				String value = VariableInterpreter.replaceVariables(expression, activityInstance);
				bizAttribute.setValue(value);
				invokeWorkItem.getAttributeList().add(bizAttribute);				
			}
		}
		bpmService.invokeProcess(invokeWorkItem);
	}
	
	public void handleException(ActivityInstance activityInstance,Exception ex) {
		ex.printStackTrace();
	}
}
